package com.zeyuan.rpcclient.netty.pro.ProtocolDesign.SelfProtocol.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

//自定义编解码器，Object为接收到的消息类型
//一般子类不能用@Sharable(编解码器能被多个channel共享使用 )，除非父类改成MessageToMessageCodec<bytebuf,message> message和bytebuf消息与消息之间转换
public class MessageCodec extends ByteToMessageCodec<Object> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        out.writeBytes(new byte[]{1,2,3,4}); //魔数
        out.writeByte(1); //版本
        //序列化算法 jdk 0 json 1
        out.writeByte(0);
        out.writeByte(0); //指令类型
        out.writeInt(123131312); //请求序号
        out.writeByte(0xff); //对齐填充
        //序列化得到byte数组
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(msg);
        byte[] bytes = byteArrayOutputStream.toByteArray();

        //长度
        out.writeInt(bytes.length);
        //写入内容
        out.writeBytes(bytes);

    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception {
        int magicNum = in.readInt();
        byte version = in.readByte();
        byte serializerType = in.readByte();
        byte messageType = in.readByte();
        int sequenceId = in.readInt();
        in.readByte(); //填充
        int length = in.readInt();
        byte[] bytes=new byte[length];
        ByteBuf byteBuf = in.readBytes(bytes,0,length);
        if (serializerType==0){ //如果是jdk序列化
            //jdk反序列化
            ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
            Object message = objectInputStream.readObject(); //这里可以强转成消息结构

        }

    }
}
